package com.xy.breakfast.controller;

import com.xy.breakfast.entity.Clients;
import com.xy.breakfast.entity.Foods;
import com.xy.breakfast.entity.Orders;
import com.xy.breakfast.entity.Products;
import com.xy.breakfast.service.ClientsService;
import com.xy.breakfast.service.FoodsService;
import com.xy.breakfast.service.OrdersService;
import com.xy.breakfast.service.ProductsService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Logger;

@Controller
public class OrdersController {

    @Autowired
    FoodsService foodsService;

    @Autowired
    OrdersService ordersService;

    @Autowired
    ClientsService clientsService;

    @Autowired
    ProductsService productsService;

    java.util.logging.Logger logger = Logger.getLogger(this.getClass().getName());

    //客户购买下单功能
    @RequestMapping("/buy")
    @ResponseBody
    @Transactional //数据库事务保证操作一定成功
    public String buy(@RequestBody Map<String,String >maps, HttpServletRequest request) throws ParseException {
        logger.info("客户开始下单了..."+new Date(System.currentTimeMillis()));

        Clients clients=(Clients) request.getSession().getAttribute("clients");
        if(clients==null) return "客户未登录，不能下单";

        //获取下单的参数
        int clientsId=clients.getId();
        int foodsId=Integer.parseInt(maps.get("foodsId"));
        int num=Integer.parseInt(maps.get("num"));

        logger.info("111111111111");
        String dateString = String.valueOf(maps.get("takeTime"));
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1 = formatter.parse(dateString);
        Timestamp timestamp = new Timestamp(date1.getTime());
        logger.info("时间"+timestamp);
        int isPack=Integer.parseInt(maps.get("isPack"));
        String phone=maps.get("phone");
        String address=maps.get("address");
        int payMethod=Integer.valueOf(maps.get("payMethod"));
        if(address.trim().length()==0) return "请填写收货地址！";
        if(phone.trim().length()==0)return "请填写电话！";

        //设置订单内容
        Foods foods=foodsService.getById(foodsId);

        //判断库存
        if(foods.getNum()<num) return "食品库存不足";

        float price=num*foods.getPrice().floatValue();

        int state=1; //未制作

        //创建订单
        Orders orders=new Orders();
        orders.setClientsId(clientsId);
        orders.setFoodsId(foodsId);
        orders.setNum(num);
        orders.setPrice(new BigDecimal(price));
        orders.setCreateTime(new Timestamp(System.currentTimeMillis()));
        orders.setTakeTime(timestamp);
        orders.setIsPack((byte)isPack);
        orders.setPhone(phone);
        orders.setAddress(address);
        orders.setPayMethod(payMethod);

        //创建制作
        Products products=new Products();
        products.setOrdersId(-1);
        products.setTakeTime(timestamp);
        products.setIsPack((byte)isPack);
        products.setAddress(address);
        products.setState(state);

        //保存订单和制作
        ordersService.save(orders);
        products.setOrdersId(orders.getId());
        productsService.save(products);

        //更新食品库存减少
        foods.setNum(foods.getNum()-num);
        foodsService.update(foods);

        return "ok";
    }

    //用户获取自己已经购买的订单信息
    @RequestMapping("/getOrdersByClientsId")
    @ResponseBody
    public List<Orders> getOrdersByClientsId(@RequestBody Map<String,String >maps, HttpServletRequest request){
        //判断用户是否登录
        Clients clients=(Clients) request.getSession().getAttribute("clients");
        if(clients==null) return null;

        //获取下单的参数
        int clientsId=clients.getId();
        List<Orders> ordersList=ordersService.getByClientsId(clientsId);

        //设置订单列表中的外键实体
        for(Orders orders:ordersList){
            orders.setClients(clientsService.getById(clientsId));
            orders.setFoods(foodsService.getById(orders.getFoodsId()));
            orders.setProducts(productsService.getById(orders.getId()));
        }

        return ordersList;
    }

    //统计每个小时订单的数量
    @RequestMapping("/getOrdersNumGroupByHour")
    @ResponseBody
    public Map<String,Object> getOrdersNumGroupByHour(){

        //查询结果
        List<Map<String ,String>> numGroupByHour=ordersService.getOrdersNumGroupByHour();

        //返回结果
        Map<String,Object> result=new HashMap<>();

        //x数据和y数据列表
        List<String> x=new ArrayList<>();
        List<String> y=new ArrayList<>();

        //封装数据到map
        for(Map<String,String> map:numGroupByHour){
            x.add(String.valueOf(map.get("x")));
            y.add(String.valueOf(map.get("y")));
        }
        result.put("x",x);
        result.put("y",y);

        return result;
    }

    @RequestMapping("/getOrdersByTypesIdDay")
    @ResponseBody
    public Map<String, Object> getOrdersByTypesIdDay(){
        //查询结果
        List<Map<String, Object>> numOrdersByTypesIdDay=ordersService.getOrdersByTypesIdDay();

        //返回结果
        Map<String,Object> result=new HashMap<>();

        //x数据和y数据列表
        List<String> x=new ArrayList<>();
        List<String> y=new ArrayList<>();
        List<String> k=new ArrayList<>();
        List<String> h=new ArrayList<>();

        //封装数据到map
        for(Map<String,Object> map:numOrdersByTypesIdDay){
            x.add(String.valueOf(map.get("x")));
            y.add(String.valueOf(map.get("y")));
            k.add(String.valueOf(map.get("k")));
            h.add(String.valueOf(map.get("h")));
        }
        result.put("x",x);
        result.put("y",y);
        result.put("k",k);
        result.put("h",h);

        return result;
    };

    @RequestMapping("/getOrdersByTypesIdHour")
    @ResponseBody
    public Map<String,Object> getOrdersByTypesIdHour() {
        //查询结果
        List<Map<String, Object>> numOrdersByTypesIdHour=ordersService.getOrdersByTypesIdHour();;

        //返回结果
        Map<String,Object> result=new HashMap<>();

        //x数据和y数据列表
        List<String> x=new ArrayList<>();
        List<String> y=new ArrayList<>();
        List<String> k=new ArrayList<>();

        //封装数据到map
        for(Map<String,Object> map:numOrdersByTypesIdHour){
            x.add(String.valueOf(map.get("x")));
            y.add(String.valueOf(map.get("y")));
            k.add(String.valueOf(map.get("k")));
        }
        result.put("x",x);
        result.put("y",y);
        result.put("k",k);

        return result;
    };
    //    不同类型销售比例图
    @RequestMapping("/getOrdersByNum")
    @ResponseBody
    public List<Map<String, Object>> getOrdersByNum(){
        return ordersService.getOrdersByNum();
    };
}
